package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> list() {
        List<Category> list =categoryMapper.list();
        List<Category> parents = list.stream().filter(c -> c.getParentId()==0).toList();
        List<Category> children = list.stream().filter(c -> c.getParentId()>0).toList();

        parents.forEach(category -> {
            findChildren(category,children);
        });
        return list;
    }
    public void findChildren(Category category,List<Category> children){
        List<Category> currentChildern= new ArrayList<>();
        List<Category> list = children.stream().filter(c -> Objects.equals(c.getParentId(), category.getId())).toList();
        if(!CollectionUtils.isEmpty(list)){
           list.forEach(c->findChildren(c,children));
        }
        category.setChildern(list);


    }
}
